#-*-coding:utf-8-*-
__author__ = 'toriycn'
from app import apps
import flask
from app.business import machinebusiness
from app.utils import RequestUtil,OtherUtil
from app.monitors.server.conf import settings
from flask.globals import request
import traceback
from werkzeug.utils import secure_filename
import os

@apps.route('/dashboard', methods=['GET'])
def dashboard_index():
    return flask.render_template('monitor/dashboard.html')

@apps.route('/machinemanager', methods=['GET'])
def machinemanager_index():
    hostlist = machinebusiness.getAllHost()
    return flask.render_template('monitor/machinemanager.html',hostlist=hostlist)

@apps.route('/filetransfer', methods=['GET'])
def filetransfer_index():
    hostlist = machinebusiness.getAllHost()
    return flask.render_template('monitor/filetransfer.html',hostlist=hostlist)

@apps.route('/execcommand', methods=['GET'])
def execcommand_index():
    hostlist = machinebusiness.getAllHost()
    return flask.render_template('monitor/commandexecute.html',hostlist=hostlist)


@apps.route('/templatemanager', methods=['GET'])
def templateemanager_index():
    returnValue = machinebusiness.getServerTemplate()
    hostlist = machinebusiness.getAllHost()
    return flask.render_template('monitor/templatemanager.html',data= returnValue.get("data"),hostlist=hostlist)


@apps.route('/getserverstatus', methods=['GET'])
def getserverstatus_page():
    hostlist = machinebusiness.getAllHost()
    #获取主机名称
    hostip = RequestUtil.get_parameter(request, 'hostselect', '127.0.0.1')
    hostInfoResult = machinebusiness.getHostInfo(hostip)
    hostdata = "error"
    if hostInfoResult.get("success"):
        hostdata = hostInfoResult.get("data")
    print(hostdata)
    return flask.render_template('monitor/serverstatus.html',hostInfo=hostdata,hostip=hostip,hostlist=hostlist)


@apps.route('/addtemplatemanager', methods=['POST'])
def templateemanager_add():
    try:
        inputTemplate = RequestUtil.get_parameter(request, 'templatename', '')
        inputInfo = RequestUtil.get_parameter(request, 'inputInfo', '')
        machinebusiness.addServerTemplate(inputTemplate)
        rst={"success":0}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/getHostListByTemplateName', methods=['GET'])
def hostlistbytemplate_get():
    try:
        inputTemplate = RequestUtil.get_parameter(request, 'templatename', '')
        returnData = machinebusiness.getAllHostByTemplate(inputTemplate)
        rst={"success":0,'data':returnData}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/getServiceListByTemplateName', methods=['GET'])
def serviceListbytemplate_get():
    try:
        inputTemplate = RequestUtil.get_parameter(request, 'templatename', '')
        returnData = machinebusiness.getAllServiceByTemplate(inputTemplate)
        rst={"success":0,'data':returnData}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/flushHostConfigToDb', methods=['GET'])
def flushHostConfigToDb():
    try:
        machinebusiness.flushHostConfigToDb()
        rst={"success":0}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/addhosttotemplate', methods=['POST'])
def templatehost_add():
    try:
        inputTemplate = RequestUtil.get_parameter(request, 'templatename', '')
        hostName = RequestUtil.get_parameter(request, 'hostName', '')
        hosts =hostName.split(',')
        machinebusiness.clearHostToTemplate(inputTemplate)
        for h in hosts:
           if h == '':
                continue
           machinebusiness.addHostToTemplate(h,inputTemplate)
        print("receive data[",inputTemplate,"]",machinebusiness.getAllHostByTemplate(inputTemplate))
        rst={"success":0}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)


@apps.route('/addservicetotemplate', methods=['POST'])
def templateservice_add():
    try:
        inputTemplate = RequestUtil.get_parameter(request, 'templatename', '')
        hostName = RequestUtil.get_parameter(request, 'hostName', '')
        hosts =hostName.split(',')
        for h in hosts:
            machinebusiness.addAService(h,inputTemplate)
        print("receive data[",inputTemplate,"]",machinebusiness.getAllHostByTemplate(inputTemplate))
        rst={"success":0}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/test', methods=['GET'])
def test_index():
    return flask.render_template('test.html')


@apps.route('/server_status_information.json', methods=['GET', 'POST'])
def server_status_infomation():
    try:
        host = RequestUtil.get_parameter(request, 'host', '')
        type = RequestUtil.get_parameter(request, 'type', '')
        rstdata = machinebusiness.getHostMonitorInfo(host = host, type=type)
        rst = {'success': 1, 'data': rstdata}
    except:
        rst = {'success': 0, 'data': 'ping error'}
    return OtherUtil.object_2_dict(rst)


@apps.route('/fileupload', methods=['POST'])
def fileupload():
    try:
        if request.method == 'POST':
           f = request.files['tranfile']
           fname = secure_filename(f.filename)  # 获取一个安全的文件名，且仅仅支持ascii字符；
           print(f.name,f.content_type,f.content_length,f.headers)
           f.save(os.path.join(settings.UPLOAD_FOLDER, fname))
           rst = {'success': "1", 'data': fname}
           return OtherUtil.object_2_dict(rst)
    except:
        traceback.print_exc()


@apps.route('/server_exec_filetrans', methods=['GET', 'POST'])
def server_exec_filetrans():
    try:
        selectHost = RequestUtil.get_parameter(request,'selectHost', '')
        print(selectHost)
        filename = RequestUtil.get_parameter(request, 'filename', '')
        remote_path =   RequestUtil.get_parameter(request, 'remote_path', '')
        rstdata = machinebusiness.filetranse(hostlist = selectHost,filename=filename,remote_path=remote_path)
        rst = {'success': 1, 'data': rstdata}
    except:
        traceback.print_exc()
        rst = {'success': 0, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/server_exec_commands', methods=['GET', 'POST'])
def server_exec_commands():
    try:
        selectHost = RequestUtil.get_parameter(request,'selectHost', '')
        remote_command =   RequestUtil.get_parameter(request, 'remote_command', '')
        rstdata = machinebusiness.execcommand(hostlist = selectHost,remote_command=remote_command)
        rst = {'success': 1, 'data': rstdata}
    except:
        traceback.print_exc()
        rst = {'success': 0, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)


@apps.route('/addhost', methods=['POST'])
def host_add():
    try:
        inputIp = RequestUtil.get_parameter(request, 'inputIp', '')
        inputPort = RequestUtil.get_parameter(request, 'inputPort', '')
        inputGroup = RequestUtil.get_parameter(request, 'inputGroup', '')
        inputUserName = RequestUtil.get_parameter(request, 'inputUserName', '')
        inputPassword = RequestUtil.get_parameter(request, 'inputPassword', '')
        h={"ip":inputIp,
           "port":inputPort,
           "group":inputGroup,
           "username":inputUserName,
           "password":inputPassword
           }

        rst = machinebusiness.addAHost(h)
        print(rst)
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)


@apps.route('/delhost', methods=['POST'])
def host_del():
    try:
        inputIp = RequestUtil.get_parameter(request, 'inputIp', '')

        rst = machinebusiness.delAHost(inputIp)
        print(rst)
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        rst = {'success':-1, 'data': 'error'}
    return OtherUtil.object_2_dict(rst)


@apps.route('/testfileupload', methods=['GET'])
def testfileupload_index():
    return flask.render_template('monitor/fileuploaddemo.html')